import {
    CanActivate,
    ExecutionContext,
    Inject,
    Injectable,
    UnauthorizedException,
} from '@nestjs/common';
import { Reflector } from '@nestjs/core';
import { Request } from 'express';
import { Observable } from 'rxjs';

@Injectable()
export class PermissionGuard implements CanActivate {
    @Inject()
    protected reflector: Reflector;

    canActivate(context: ExecutionContext): boolean | Promise<boolean> | Observable<boolean> {
        const request: Request = context.switchToHttp().getRequest();
        if (!request.user) {
            return true;
        }
        const { permissions } = request.user;

        const requirePermissions = this.reflector.getAllAndOverride('require-permission', [
            context.getClass(),
            context.getHandler(),
        ]);
        if (!requirePermissions) {
            return true;
        }
        for (const reper of requirePermissions) {
            const found = permissions.find((item) => item.code === reper);
            if (!found) {
                throw new UnauthorizedException('暂无权限');
            }
        }
        return true;
    }
}
